import Books from '../../decormodel/books'
import { sequelize } from '../../BaseDao'
import { Op } from 'sequelize'
import { getNoReptItem } from '../../../modules/commontypes'

class BookDao {
  static bookDao: BookDao = new BookDao()
  async findBooksByThirdCtgyId(thirdctgyid: number, offset: number, pageSize: number) {
    let data: any[] = []
    let dataLength: any[]
    if (thirdctgyid == 0) {
      const sql = `select count(*) from books`
      dataLength = (await sequelize.query(sql))[0]
      data = await Books.findAll({
        raw: true,
        limit: pageSize,
        offset,
      })
    } else {
      const sql = `select count(*) from books where thirdctgyid = ${thirdctgyid}`
      dataLength = (await sequelize.query(sql))[0]
      data = await Books.findAll({
        raw: true,
        where: {
          thirdctgyid,
        },
        limit: pageSize,
        offset,
      })
    }
    const paging = {
      pageNum: offset,
      pageSize,
      length: dataLength[0]['count(*)'],
      hasMoreData: false,
    }
    if (data.length === 0 || offset > dataLength[0]['count(*)']) {
      paging.hasMoreData = true
    }

    return { data, paging }
  }
  async findBookRisefall(thirdctgyid: number, risefall: string) {
    if (thirdctgyid == 0) {
      return await Books.findAll({
        raw: true,
        order: [['originalprice', risefall]],
      })
    } else {
      return await Books.findAll({
        raw: true,
        order: [['originalprice', risefall]],
        where: {
          thirdctgyid,
        },
      })
    }
  }

  async findBookDetail(ISBN: string) {
    return await Books.findOne({
      raw: true,
      where: {
        ISBN,
      },
    })
  }

  async findBooksByAutoCompKeyword(autocompKeyword: string): Promise<Books[]> {
    return await Books.findAll({
      raw: true,
      where: {
        bookname: {
          [Op.like]: `%${autocompKeyword}`,
        },
      },
    })
  }

  async findPublishersByAutoCompKey(autocompKeyword: string) {
    const book = await Books.findAll({
      attributes: ['publishid', 'publishername'],
      raw: true,
      where: {
        bookname: {
          [Op.like]: `%${autocompKeyword}%`,
        },
      },
    })
    return getNoReptItem(book, 'publishid')
  }

  async findBksByPublishIds(publishIds: number) {
    return await Books.findAll({
      raw: true,
      // @ts-ignore
      where: {
        publishid: {
          [Op.in]: publishIds,
        },
      },
    })
  }
}

export default BookDao.bookDao
